import util from 'utils/util.js';
const baseUrl = 'http://dev.banmachewu.com/crm/api';

function request(opt) {
	var header = {};
	var fullUrl = opt.url;
	/**
	 * @description md5验证标识
	 * @param {String} url
	 **/
	var getUserToken = function(url) {
		var result = "-99";
		try {
			var p = "cgs";
			var ms = new Date().getMilliseconds();
			if (ms < 100) {
				ms += 100;
			}
			var token;
			if (url.length > 32) {
				token = p + url.substring(8, 32) + ms;

			} else {
				token = p + url.substring(9) + ms;
			}
			if (util.md5) {
				result = ms + util.md5(token);
				console.log(result);
			}
		} catch (e) {
			result = "-99";
		}
		return result;
	}

	var setHeader = function(name, value) {
		header[name.toLowerCase()] = [name, value];
	};
	if (opt.header) {
		for (var name in opt.header) setHeader(name, opt.header[name]);
	} else {
		opt.header = {};
	}
	//判断type非空
	if (opt.method) {
		opt.method = opt.method.toUpperCase();
	} else {
		opt.method = "GET";
	}
	if (opt.method == "POST") {} else {
		if (opt.data) {
			var qurl = [];
			for (var k in opt.data) {
				qurl.push(k + "=" + encodeURIComponent(opt.data[k]));
			}
			fullUrl = fullUrl + "?" + qurl.join("&");
		}
	}
	//统一添加headr
	header.Authorization = "Basic " + getUserToken(fullUrl);
	Object.assign(opt.header, header);
	uni.request(opt);
}


// 登录
export function login(data) {
	return new Promise(function(resolve, reject) {
		uni.request({
			url: baseUrl + '/Users/Login',
			data: data,
			method: 'POST',
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		})
	})
}

//待办统计
export function toToStatistic(userId) {
	return new Promise(function(resolve, reject) {
		request({
			url: baseUrl + '/Todo/GetStatistic',
			data: {
				userId: userId
			},
			method: 'GET',
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		})
	})
}

//今日线索
export function clueStatistic(userId) {
	return new Promise(function(resolve, reject) {
		request({
			url: baseUrl + '/Clue/GetStatistic',
			data: {
				userId: userId
			},
			method: 'GET',
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		})
	})
}

//获取线索
export function clubList(data) {
	return new Promise(function(resolve, reject) {
		console.log('1234');
		request({
			url: baseUrl + '/Clue/GetPages',
			data: data,
			method: 'POST',
			success: (res) => {
				console.log('1234');
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		})
	})
}
